package com.example.listossimage.util;

import org.apache.commons.io.IOUtils;
import org.lionsoul.ip2region.*;
import org.springframework.core.io.ClassPathResource;
import sun.nio.ch.IOUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;

public class IPUtil {

    /**
     * 获取IP地址
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if ("0:0:0:0:0:0:0:1".equals(ip)) {
            ip = "127.0.0.1";
        }
        if (ip.split(",").length > 1) {
            ip = ip.split(",")[0];
        }
        return ip;
    }

    /**
     * 根据IP地址获取城市
     * @param ip
     * @return
     */
    public static String getCityInfo(String ip) {

        try {
            ClassPathResource resource = new ClassPathResource("/templates/ip2region.db");
            InputStream inputStream = resource.getInputStream();
            byte[] dbBinStr = IOUtils.toByteArray(inputStream);
            DbConfig config = new DbConfig();
            DbSearcher searcher = new DbSearcher(config, dbBinStr);
            // 查询算法memory，采用二进制方式初始化DBSearcher需要使用MEMORY_ALGORITYM，
            //否则会抛出null。
            Method method = searcher.getClass().getMethod("memorySearch", String.class);
            String area = ((DataBlock) method.invoke(searcher, ip)).getRegion();
            return area;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
